<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="关键字">
        <el-input v-model="queryParams.keyword" placeholder="请输入关键字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文件状态" prop="fileStatusValue">
        <el-select v-model="queryParams.fileStatusValue" placeholder="请选择文件状态" clearable>
          <el-option v-for="dict in dict.type.sys_file_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:file:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:filet:edit']"
          >修改</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:file:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:file:export']"
          >导出</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="printBox"
          :disabled="multiple"
          v-hasPermi="['system:file:print']"
          >打印</el-button
        >
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table fit v-loading="loading" border :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="fileManagerId" width="120" />
      <el-table-column label="受控编号" prop="fileCode" :show-overflow-tooltip="true" width="150">
        <template slot-scope="scope">
          <el-link @click="handleDetailDiag(scope.row)" type="primary">{{
            scope.row.fileCode
          }}</el-link>
        </template></el-table-column>
      <el-table-column min-width="180" label="文件名称" prop="fileName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link @click="handleDetailDiag(scope.row)" type="primary">{{
            scope.row.fileName
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="文件预览" prop="fileCode" :show-overflow-tooltip="true" width="150">
        <template slot-scope="scope">
          <el-link type="primary" :href="baseUrl + item" target="_blank" v-for="item in scope.row.fileUrl&&scope.row.fileUrl.split(',')">
            {{ getFileName(item) }}
          </el-link>
        </template></el-table-column>
      <el-table-column min-width="150" :show-overflow-tooltip="true" align="center" label="关联员工" prop="userName" />

      <el-table-column label="文件类型" min-width="180" prop="fileTypeLabel" :show-overflow-tooltip="true" />
      <el-table-column min-width="150" label="文件状态" prop="fileStatusLabel" :show-overflow-tooltip="true" />

      <el-table-column label="关键字" prop="keyword" :show-overflow-tooltip="true" />

      <el-table-column label="文件实施日期" prop="startDate" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="创建人" prop="createByName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="创建日期" prop="createTime" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="修改人" prop="updateByName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="修改日期" prop="updateTime" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="是否显示" :show-overflow-tooltip="true" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row,'isShow')"
          ></el-switch>
        </template></el-table-column>
        <el-table-column label="是否置顶" :show-overflow-tooltip="true" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRecommend"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row,'isRecommend')"
          ></el-switch>
        </template></el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        width="250"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['system:file:ly']"
            @click="handleCode(scope.row)"
            >领用</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['system:file:ff']"
            @click="handleSend(scope.row)"
            >分发</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-hasPermi="['system:file:info']"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:file:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:file:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :visible.sync="showCode" title="领用二维码" width="300px" append-to-body>
      <div style="text-align: center">
        <vue-qr :text="textUrl" :size="200"></vue-qr>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showSend" title="分发" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="员工" prop="userId">
          <UserDialog placeholder="请选择员工" @change="changeUser" v-model="form.userId"></UserDialog>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button size="mini" @click="showSend = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveSend">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 打印模板位置 -->
    <PrintBox :pageNum="queryParams.pageNum" :total="total" :printRow="printList" :checkNum="18"
      :checkLabel="'contentList'" id="printBox">
      <template slot="title" slot-scope="scope">
        试验室受控文件清单 STET/B/03-8
        <div style="font-size: 14px; margin-top: 5px">
          <span v-if="zlcode.includes(Number(fileTypeValue))">（质量活动记录表格 （通用类、标定类、各类试验物质及设备验收类、
            辅助类、期间核查类）</span>

          <span v-if="wlwjcode.includes(Number(fileTypeValue))">(往来文件(本公司发文、上级单位来文、外单位来文))</span>
          <span v-if="[6, 15, 16].includes(Number(fileTypeValue))">(质量手册、资源手册、程序文件)</span>
          <span v-if="[7, 8, 10, 11, 12, 113, 14].includes(Number(fileTypeValue))">(作业指导书)</span>
          <span v-if="fileTypeValue == 22">(检测方法)</span>
        </div>
      </template>
      <template slot-scope="scope">
        <!-- 表格  class  table-page  必须-->
        <table style="border-collapse: collapse" border="1" cellspacing="0" class="table-page">
          <thead>
            <tr class="table_header">
              <th style="width: 20mm">序号</th>
              <th style="width: 30mm">受控编号</th>
              <th style="width: 45mm">文件名</th>
              <th style="width: 65mm">文件类型</th>
              <th style="width: 55mm">文件状态</th>
              <th style="width: 50mm">文件废止日期</th>
              <th style="width: 50mm">文件实施日期</th>
              <th style="width: 50mm">备注</th>
              <th style="width: 50mm" v-if="wlwjcode.includes(Number(fileTypeValue))">
                文件下发日期
              </th>
            </tr>
          </thead>
          <!-- 同列表接口数据 -->
          <tbody>
            <tr v-for="(e, i) in 18">
              <td>
                {{ scope.item.contentList[i] ? i + 1 : "" }}
              </td>
              <td>
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].fileCode) ||
                  ""
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].fileName
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].fileTypeLabel
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].fileStatusLabel
                }}
              </td>

              <td>
                {{
                  scope.item.contentList[i] &&
                  parseTime(scope.item.contentList[i].endDate, "{y}-{m}-{d}")
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  parseTime(scope.item.contentList[i].startDate, "{y}-{m}-{d}")
                }}
              </td>
              <td></td>
              <td v-if="wlwjcode.includes(Number(fileTypeValue))">
                {{
                  scope.item.contentList[i] &&
                  parseTime(scope.item.contentList[i].createTime, "{y}-{m}-{d}")
                }}
              </td>
            </tr>
          </tbody>
        </table>
      </template>
    </PrintBox>
    <Detail ref="Detail" :id="id"></Detail>
  </div>
</template>
<script>
import store from "@/store";
import printStyle from "@/utils/print.js";
import {
  updategFileManager,
} from "@/api/system/fileManager.js";
import { listFileManager, delFileManager } from "@/api/system/fileManager.js";
import { fileGetAdd } from "@/api/system/fileManagerRecord.js";
import Detail from "@/views/system/file/detail.vue";
export default {
  name: "listFileManager",
  components: {
    Detail,
  },
  dicts: ["sys_file_type", "sys_file_status"],
  data() {
    return {
      baseUrl: this.$VUE_APP_IMG_API,
      id: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      dataList: [],
      // 弹出层标题
      // 日期范围
      dateRange: [],
      // 数据范围选项
      queryParams: {
        fileTypeValue: 3,
        pageNum: 1,
        keyword: undefined,
        fileStatusValue: undefined,
        pageSize: 10,
      },
      showCode: false,
      current: {},
      showSend: false,
      form: {},
      rules: {
        userId: [
          {
            required: true,
            message: "请选择员工",
            trigger: "change",
          },
        ],
      },
      textUrl: "",
      infos: [],
      printList: [],
      fileTypeValue: 0,
      zlcode: [21, 20, 19, 18, 17], //质量活动记录表格
      wlwjcode: [2, 3, 4, 5], //外来文件
    };
  },
  // 22--
  created() {
    this.getList();
  },
  methods: {
    handleStatusChange(row,lab) {
      let text = lab == 'isRecommend'?row.isRecommend == 1 ? "置顶" : "取消置顶":row.isShow == 1 ? "显示" : "隐藏";
      this.$modal
        .confirm('确认要"' + text + '""' + row.fileName + '"文件吗？')
        .then(function () {
          return updategFileManager(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList()
        })
        .catch(function (e) {
          if(lab=='isShow'){
            row.isShow = row.isShow == "0" ? "1" : "0"
          }else{
            row.isRecommend = row.isRecommend == 0 ? 1 : 0
            console.log(row.isRecommend);
          }
        });
    },
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      if (this.infos.length) {
        this.printList = [
          {
            contentList: this.infos,
          },
        ];
      } else {
        //反之打印当前整个列表
        this.printList = [
          {
            contentList: this.dataList,
          },
        ];
      }
      // 7, 8, 10, 11, 12, 113, 14
      // 6, 15, 16
      // zlcode
      // wlwjcode
      let flag = false;
      let e = this.printList[0].contentList[0].fileTypeValue;
      if ([7, 8, 10, 11, 12, 113, 14].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => ![7, 8, 10, 11, 12, 113, 14].includes(Number(e.fileTypeValue))
        );
      } else if ([6, 15, 16].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => ![6, 15, 16].includes(Number(e.fileTypeValue))
        );
      } else if (this.zlcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => !this.zlcode.includes(Number(e.fileTypeValue))
        );
      } else if (this.wlwjcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => !this.wlwjcode.includes(Number(e.fileTypeValue))
        );
      }
      if (flag) {
        this.$modal.msgWarning("多选数据 请保持类型一致");
        return;
      }
      this.fileTypeValue = this.printList[0].contentList[0].fileTypeValue;

      setTimeout(() => {
        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle(),
        });
      }, 500);
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
         table,
      table tr th,
      table tr td {
        height: 10mm;
        padding:7px
      }
      tr {
        page-break-inside: avoid;
      }
      .table_header{
        font-size:16px;
      }
      `;
    },
    changeUser(e) {
      this.form.user = e.nickName;
    },
    saveSend() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          (this.form.fileManagerId = this.current.fileManagerId),
            (this.form.statusValue = 2),
            (this.form.num = 1);
          (this.form.optUserId = store.state.user.id),
            (this.form.optUser = store.state.user.nickName),
            (this.form.optTime = this.parseTime(new Date())),
            fileGetAdd(this.form).then((response) => {
              this.$modal.msgSuccess("分发成功");
              this.showSend = false;
              this.getList();
            });
        }
      });
    },
    handleSend(e) {
      this.form = {};
      this.current = e;
      this.showSend = true;
    },
    userSelect() {
      userSelect().then((response) => {
        this.userList = response.data;
      });
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    getList() {
      this.loading = true;
      listFileManager(
        this.addDateRangeTime(this.queryParams, this.dateRange)
      ).then((response) => {
        this.dataList = response.rows;
        console.log(this.dataList);
        this.total = response.total;
        this.loading = false;
      });
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.typeValue = data.value;
      this.handleQuery();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDetail(row) {
      this.$router.push("./addFile?isInfo=true&id=" + row.fileManagerId);
    },
    handleDetailDiag(e) {
      this.$refs.Detail.show(e.fileManagerId);
    },
    handleCode(res) {
      this.textUrl =
        process.env.VUE_APP_CODE_API + "fileManager?id=" + res.fileManagerId;

      this.showCode = true;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.fileManagerId);
      this.infos = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("./addFile");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const configId = row.fileManagerId || this.ids;
      this.$router.push("./addFile?isEdit=true&id=" + configId);
    },
    handleExport() {
      this.download(
        "system/fileManager/export",
        {
          ...this.queryParams,
        },
        `文件记录表_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}")}.xlsx`
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.fileManagerId || this.ids;
      let name = this.checkRow(
        userIds,
        this.dataList,
        "fileManagerId",
        "DELETE",
        "fileName"
      );
      this.$modal
        .confirm('是否确认删除文件名称为"' + name + '"的数据项？')
        .then(function () {
          return delFileManager(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
